package edu.xidian.forum.controller;

import cn.hutool.core.net.URLDecoder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.xidian.forum.common.Result;
import edu.xidian.forum.service.PostService;
import edu.xidian.forum.vo.PostVO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/search")
public class SearchController {

    @Resource
    private PostService postService;

    @GetMapping("/searchList")
    public Result<Page<PostVO>> searchList(@RequestParam("keyword") String keyword,
                                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                           @RequestParam("tab") String tab) {
        Page<PostVO> results = postService.searchByKey(
                encodeForSQL(URLDecoder.decode(keyword, StandardCharsets.UTF_8)), new Page<>(pageNum, pageSize), tab);
        return Result.success(results);
    }

    @GetMapping("/searchByTag")
    public Result<Page<PostVO>> searchByTag(@RequestParam("keyword") String tagName,
                                            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<PostVO> results = postService.searchByTag(
                encodeForSQL(URLDecoder.decode(tagName, StandardCharsets.UTF_8)), new Page<>(pageNum, pageSize));
        return Result.success(results);
    }

    private String encodeForSQL(String str) {
        return str.replace("\\", "\\\\")
                .replace("%", "\\%")
                .replace("_", "\\_")
                .replace("*", "\\*")
                .replace("'", "''");
    }
}
